package com.xiaok.mobileredis.controller;

import com.xiaok.mobileredis.request.RedPacketReq;
import com.xiaok.mobileredis.enums.StatusCode;
import com.xiaok.mobileredis.response.BaseResponse;
import com.xiaok.mobileredis.service.RedPacketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

@RestController
@EnableAsync //能够使用移步 ,如果在方法里面 @Async 处理该方法会创建一个线程
public class RedPacketController {
    private static final String PREFIX="redpacket";

    private static final Logger logger= LoggerFactory.getLogger(RedPacketController.class);

    @Autowired
    private RedPacketService service;

    @PostMapping(value = PREFIX+"/out",consumes = MediaType.APPLICATION_JSON_VALUE)
    public BaseResponse<String> out(@Validated @RequestBody RedPacketReq redPacketReq, BindingResult result){
        if(result.hasErrors()){
            return new BaseResponse<>(StatusCode.InvalidParams);
        }
        //校验成功，发红包
        BaseResponse<String> response=new BaseResponse<>(StatusCode.Success);
        try {
            String redId=service.handOut(redPacketReq);
            response.setData(redId);//返回唯一标识
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    /**
     * 抢红包接口
     * @param userId
     * @param redId
     * @return
     */
    @GetMapping(value = PREFIX+"/rob")
    public BaseResponse<String> rob(@RequestParam Integer userId,@RequestParam String redId){

        BaseResponse<String> response=new BaseResponse<>(StatusCode.Success);

        try { //抢红包逻辑
            BigDecimal money=service.rob(userId,redId);
            if(money!=null){
                response.setData(money.toString());
            }else{
                response=new BaseResponse<>(StatusCode.Fail.getCode(),"no storage");
            }

        } catch (Exception e) {
            logger.error("抢红包发生异常：userId={} redId={}",userId,redId,e.fillInStackTrace());
            response= new BaseResponse<>(StatusCode.Fail.getCode(), e.getMessage());
        }
        return response;
    }

}
